package com.github.aloxc.plugin.restplus.listener;

import com.github.aloxc.plugin.restplus.entity.Show;
import com.github.aloxc.plugin.restplus.i18n.I18Bundle;
import com.github.aloxc.plugin.restplus.navigator.RestServiceDetail;
import com.github.aloxc.plugin.restplus.popup.PopupBalloon;

import javax.swing.text.BadLocationException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;

public class SearchActionListener implements ActionListener {
    private RestServiceDetail restServiceDetail;

    public SearchActionListener(RestServiceDetail restServiceDetail){

        this.restServiceDetail = restServiceDetail;
    }
    @Override
    public void actionPerformed(ActionEvent event) {
        Show show = Show.get();
        if (show == Show.CODE) {
            try {
                if (restServiceDetail.getSearchKey() != null && restServiceDetail.getResponseTextArea() != null) {
                    restServiceDetail.getResponseTextArea().search(restServiceDetail.getSearchKey());
                }
            } catch (BadLocationException e) {
                Writer result = new StringWriter();
                PrintWriter printWriter = new PrintWriter(result);
                e.printStackTrace(printWriter);
                String msg = result.toString();
                msg.replaceAll("\\\\r\\\\n", "<br>");
                PopupBalloon.showNotification(restServiceDetail.getProject(), I18Bundle.getMessage("com.github.aloxc.plugin.restplus.search.exeception.text") + "<br>" + msg, false);
            }
        } else {
            if (restServiceDetail.getSearchKey() != null) {
                restServiceDetail.findTreeChildValue(restServiceDetail.getSearchKey().getText());
            }
        }
    }
}
